﻿using PlutoStudio.Net;
using PlutoStudio.Net.Messages;
using PlutoStudio.Net.Tcp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test.Server
{
    class Program
    {
        static int count=0;
        static void Main(string[] args)
        {
            var listener = new TcpListener();
            listener.Accepted += listener_Accepted;
            listener.StartAccept();
            Console.WriteLine("开始监听！");
            Console.ReadKey();
        }

        static void listener_Accepted(object sender, AcceptedEventArgs e)
        {
            Console.WriteLine("接受到来自{0}的请求",e.TcpClient.RemoteEndPoint);
            e.TcpClient.Received += TcpClient_Received;
            e.TcpClient.Closed += TcpClient_Closed;
            e.TcpClient.Sended += TcpClient_Sended;
            e.TcpClient.BeginReceive();
            for (int i = 0; i < 100; i++)
            {
                var message = new Message(1, (byte)i);
                message.MessageId = (UInt16)i;
                Console.WriteLine(message.MessageId);
                message.SetData("测试信息"+i);
                e.TcpClient.Send(message);
                System.Threading.Thread.Sleep(10);
            }
        }

        static void TcpClient_Sended(object sender, EventArgs e)
        {
           // Console.WriteLine("消息发送成功！");
        }

        static void TcpClient_Closed(object sender, EventArgs e)
        {
            var client = sender as TcpClient;
            Console.WriteLine("来自{0}的连接已经断开！",client.RemoteEndPoint);
            client.Received -= TcpClient_Received;
            client.Sended -= TcpClient_Sended;
            client.Closed -= TcpClient_Closed;
        }

        static void TcpClient_Received(object sender, ReceivedEventArgs e)
        {
            var client = sender as TcpClient;
            var content = Encoding.UTF8.GetString(e.Message.Content);
            //System.Threading.Thread.Sleep(2000);
            //Console.WriteLine("接收到消息:{0},{1},{2}", e.Message.Flag, e.Message.Code, content);
            //Console.WriteLine("接收到{0}条消息",System.Threading.Interlocked.Increment(ref count));
            e.Message.StatusCode = 200;
            client.Send(e.Message);
        }
    }
}
